﻿// Copyright 2013 Ronald Schlenker, www.technewlogic.de.
// 
// This file is part of Byond.
// 
// Byond is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
// 
// Byond is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with Byond.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.IO;
using Byond.EnsembleLibrary;
using Byond.Logging;
using Microsoft.Win32;
using Utils.DialogManagement;

namespace Byond.Frontend
{
	class EnsembleAdministrationWorkflows
	{
		private readonly IDialogManager _dialogManager;
		private readonly Library _library;
		private readonly IUserLogger _logger;

		public void Delete(string path)
		{
			TryAndAsk(
				() => _library.DeleteItem(path),
				"Really delete this patch?",
				"Could not delete item.");
		}

		public void NewFolder(string path)
		{
			var dialog = _dialogManager.CreateInputDialog(
				"Enter folder name", DialogMode.OkCancel);
			dialog.Ok = () =>
			{
				var folderName = dialog.Value;
				// TODO: Exists validieren
				// TODO: PatchName / C# Klasse validieren

				if (string.IsNullOrWhiteSpace(folderName))
				{
					_dialogManager.CreateMessageDialog("Folder name is not valid.", DialogMode.Ok).Show();
				}
				else
				{
					Try(
						() => _library.CreateFolder(path, folderName),
						"Could not create the folder.");
				}
			};
			dialog.Show();
		}

		public void NewItem(string folderPath)
		{
			var dialog = _dialogManager.CreateInputDialog(
				"Enter patch name", DialogMode.OkCancel);
			dialog.Ok = () =>
				{
					var patchName = dialog.Value;
					// TODO: Exists validieren
					// TODO: PatchName / C# Klasse validieren

					if (string.IsNullOrWhiteSpace(patchName))
					{
						_dialogManager.CreateMessageDialog("Patch name is not valid.", DialogMode.Ok).Show();
					}
					else
					{
						Try(
							() => _library.CreateItem(folderPath, patchName),
							"Could not create the patch.");
					}
				};
			dialog.Show();
		}

		private void TryAndAsk(Action del, string question, string userErrorMessage)
		{
			var dialog = _dialogManager.CreateMessageDialog(question, DialogMode.YesNo);
			dialog.Yes = () => Try(del, userErrorMessage);
			dialog.Show();
		}

		private void Try(Action del, string userErrorMessage)
		{
			try
			{
				del();
			}
			catch (Exception e)
			{
				_logger.Log(e.ToString());
				_dialogManager.CreateMessageDialog(userErrorMessage, "Error", DialogMode.Ok);
			}
		}
	}
}
